package com.stephen.redisdemo.reference;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * @author: stephen
 * @create: 2020-03-03 15:09
 * @description: WeakHashMap
 * 如果key为空,则发生gc时,该entry就会被清除
 */
public class WeakHashMapDemo {

    public static void main(String[] args) {
        // myHashMap();
        System.out.println("--------------");
        myWeakHashMap();
    }

    public static void myWeakHashMap() {
        WeakHashMap<String,String> map = new WeakHashMap<>();
        String key = "bb";
        String value = "bbb";
        map.put(key,value);
        System.out.println(map); // {aa=aaa}
        key = null;
        System.out.println(map); // {aa=aaa}
        System.gc();
        System.out.println(map); // {} ?
    }

    public static void myHashMap() {
        Map<String,String> map = new HashMap<>();
        String key = "aa";
        String value = "aaa";
        map.put(key,value);
        System.out.println(map); // {aa=aaa}
        key = null;
        System.out.println(map); // {aa=aaa}
        System.gc();
        System.out.println(map); // {aa=aaa}

    }
}
